package com.ltt.handler;

import com.alibaba.fastjson.JSON;
import com.ltt.annotation.NoAuth;
import com.ltt.common.RedisKey;
import com.ltt.common.UserThreadLocal;
import com.ltt.dao.vo.UserVo;
import com.ltt.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ‘李天泰’
 * @version 1.0
 * @description: TODO
 * @date 2023/5/1 14:39
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if (handlerMethod.hasMethodAnnotation(NoAuth.class)) {
            return true;
        }
        String token = request.getHeader("Authorization");
        boolean verify = JWTUtils.verify(token);
        if (!verify) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("未登录");
            return false;
        }
        String userJson = (String) redisTemplate.opsForValue().get(RedisKey.TOKEN + token);
        if (StringUtils.isBlank(userJson)) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("未登录");
            return false;
        }
        UserVo userVo = JSON.parseObject(userJson, UserVo.class);
        UserThreadLocal.put(userVo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
